<template>
  <div class="box">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="请输入用户名" v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input placeholder="请输入密码" type="password" v-model="ruleForm.password"></el-input>

      </el-form-item>
      <el-form-item>
        <el-button :loading="loading" type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import request from '@/utils/request'
import request from '@/utils/request'
export default {
  data() {
    return {
      loading:false,
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username:
          { required: true, message: '请输入用户名', trigger: 'blur' },
        password:
          { required: true, message: '请输入密码', trigger: 'change' },

      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading=true;
          request.post('/users/login',this.ruleForm)
          .then(res=>{
            this.loading=false;
            console.log(res);
            if(res.data.code==1){
              this.$message.success("登录成功");
              const token=res.data.token;
              localStorage.token=token;
              this.$router.push('/main')
            }else{
              this.$message.error("登录失败")
            }
          })
          .catch(err=>{
            this.loading=false;
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;

}
</style>